package com.typing.battle.activity;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.w3c.dom.Element;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.typing.battle.R;
import com.typing.battle.util.C2dmUtil;
import com.typing.battle.util.PreferenceMgr;
import com.typing.battle.util.ServerComunicationUtil;
import com.typing.battle.value.ServerComunicationDTO;

public class TypingBattleLoginActivity extends Activity implements android.view.View.OnClickListener {
	
	private Button btn_signin, btn_regi;
	
	private EditText et_id, et_pwd;
	private TextView tv_forgot_id, tv_forgot_pwd;
	
	private final String SAVE_USERID= "SAVE_USERID";
	private final String SAVE_USERPWD= "SAVE_USERPWD";
	private final String SAVE_COUNTRYLIST= "SAVE_COUNTRYLIST";
	
	public final static int POPUP_NONE   = -1;
	public final static int POPUP_COUNTRY = 0;
	
	private final String SAVE_POPUP = "SAVE_POPUP";
	public int popupKind = POPUP_NONE;
	
	private AlertDialog dialog;

	private int setCountry = 0;
	private String strCountry = "";
	
	private String userCountry;
	private String userLanguage;

	public final static int LOGIN_RESULT_OK   = 1000;
	public final static int LOGIN_RESULT_REGISTER   = 1001;
	public final static int LOGIN_RESULT_FAILED = 9999;
	
	private PreferenceMgr mgr;
	
	public String getScreenId() {
		return "SE14";
	}
	
//	private RWPreference prefer;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);		
//		prefer = RWPreference.getInstance(this);
		
		mgr = PreferenceMgr.getInstance(this);
		if (!"".equals(mgr.getData(PreferenceMgr.USER_EMAIL_KEY, ""))) {
			autoLogin();
			//ServerComunicationUtil.chatRoomAction(dto,this);
		}
		
		init(savedInstanceState);
		
	}
	
	@SuppressWarnings("unchecked")
	private void init(Bundle savedInstanceState){
		setContentView(R.layout.battle_login);
		
				
		et_id = (EditText) findViewById(R.id.et_id);
		et_pwd = (EditText) findViewById(R.id.et_pwd);
		
		tv_forgot_id = (TextView) findViewById(R.id.tv_forgot_id);
		tv_forgot_pwd = (TextView) findViewById(R.id.tv_forgot_pwd);
		tv_forgot_id.setOnClickListener(this);
		tv_forgot_pwd.setOnClickListener(this);
		
		btn_signin = (Button) findViewById(R.id.btn_signin);
		btn_regi= (Button) findViewById(R.id.btn_regi);
		
		btn_signin.setOnClickListener(this);
		btn_regi.setOnClickListener(this);
		
		// 한글 Font Bold 처리
//		tv_sign.setPaintFlags(tv_sign.getPaintFlags() | Paint.FAKE_BOLD_TEXT_FLAG);  
//		tv_regi.setPaintFlags(tv_regi.getPaintFlags() | Paint.FAKE_BOLD_TEXT_FLAG);  

//		userCountry = prefer.getData(Define.SHARED_LOGIN_COUNTRYCODE, "");
//		userLanguage = prefer.getData(Define.SHARED_LOGIN_LANGUAGECODE, "");
//		
//		if(savedInstanceState != null){
//			String strSaveUserID = savedInstanceState.getString(SAVE_USERID);
//			et_id.setText(strSaveUserID);
//			
//			String strSaveUserPWD = savedInstanceState.getString(SAVE_USERPWD);
//			et_pwd.setText(strSaveUserPWD);
//
//			int popup = savedInstanceState.getInt(SAVE_POPUP);
//			if(popup == POPUP_COUNTRY){
//				Util.log("POPUP_COUNTRY");
//				popupKind = POPUP_COUNTRY;
//				countrylist = (ArrayList<CountryLanguageInfo>) savedInstanceState.getSerializable(SAVE_COUNTRYLIST);
//				showDialog_Country();
//			} 
//			
//			userCountry = prefer.getData(Define.SHARED_LOGIN_COUNTRYCODE, "AU");
//			userLanguage = prefer.getData(Define.SHARED_LOGIN_LANGUAGECODE, "EN");
//		}
//		
//		showKeyboard(true, et_id);

	}
	
//	@Override
//	protected void onSaveInstanceState(Bundle outState) {
//		
//		outState.putString(SAVE_USERID, et_id.getText().toString());
//		outState.putString(SAVE_USERPWD, et_pwd.getText().toString());
//		
//		outState.putInt(SAVE_POPUP, popupKind);
//		
//		if(popupKind == POPUP_COUNTRY)
//			outState.putSerializable(SAVE_COUNTRYLIST, countrylist);
//		
//		try{
//			if(dialog != null)
//				dialog.dismiss();
//		} catch(Exception e){
//			Util.logError(e);
//		}
//	}

	@Override
	public void onClick(View v) {
		Intent intent = null;
		
		switch(v.getId()){
		case R.id.btn_regi:
			intent = new Intent(this,TypingBattleIndexActivity.class);
			startActivityForResult(intent,1000);
			break;
		case R.id.btn_signin:
			checkInput();
			break;
		
//		case R.id.tv_forgot_id:
//				intent = new Intent(this, WebActivity.class);
//				String url =  "http://" + prefer.getData(Define.SHARED_LGWorld_Domain, "www.lgworld.com") + prefer.getData(Define.SHARED_FORGOT_ID_URL, "");
//				url = url + "?countryCode=" + userCountry + "&languageCode=" + userLanguage;
//				intent.putExtra("url", url);
//				Util.startActivity(this, intent);
//			
//			break;
//		case R.id.tv_forgot_pwd:
//
//				intent = new Intent(this, WebActivity.class);
//				String url = "http://" + prefer.getData(Define.SHARED_LGWorld_Domain, "www.lgworld.com") + prefer.getData(Define.SHARED_FORGOT_PWD_URL, "");
//				url = url + "?countryCode=" + userCountry + "&languageCode=" + userLanguage;
//				intent.putExtra("url", url);
//				Util.startActivity(this, intent);
//			
//			break;
		}
	}
	
//	private void checkLogin(){
//		String userid = et_id.getText().toString().trim();
//		String pwd = et_pwd.getText().toString().trim();
//
//		Util.log("userid = " + userid); 
//		Util.log("pwd = " + pwd); 
//		
//		if(userid.equals("") || userid.length() == 0){
//			// 오류 팝업 또는 오류 메세지를 띄운다.
//			Util.log(" ID error =" + R.string.sp_Reg_ID_error_1_NORMAL);
//			RWDialog.showAlert(this,  getString(R.string.app_name), getString(R.string.sp_Reg_ID_error_1_NORMAL));
//			return;
//		} else if (userid.length() < 4 || userid.length() > 12){
//			// 문자열 길이 제한
//			Util.log(" ID error =" + R.string.sp_Reg_ID_error_3_NORMAL);
//			RWDialog.showAlert(this,  getString(R.string.app_name), getString(R.string.sp_Reg_ID_error_3_NORMAL));
//			return;
//		} else if (!Util.isLowercaseAndNumeric(userid)){
//			// 영문 숫자만 가능
//			Util.log(" ID error =" + R.string.sp_Reg_ID_error_4_NORMAL);
//			RWDialog.showAlert(this,  getString(R.string.app_name), getString(R.string.sp_Reg_ID_error_4_NORMAL));
//			return;
//		}
//		
//		if (pwd.equals("")){
//			return;
//		}
//		
//		HashMap<String, String> map = new HashMap<String, String>();
//		map.put("userid", userid);
//		map.put("password", pwd);
//		map.put("passwordex", Util.makeSHA512(userid, pwd));
//		
//		//new LoginAsync(this, Define.SERVER_URL_LG_LOGIN, map).execute("");
//		
//		InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//		mgr.hideSoftInputFromWindow(et_id.getWindowToken(), 0);
//		mgr.hideSoftInputFromWindow(et_pwd.getWindowToken(), 0);
//		
//		getLoginInfo(map);
//		
//	}

//	@Override
//	public void onSyncComplete(int resultCode) {
//		if (resultCode == OnDataSyncCompleteListener.RESULT_COUNTRY) {
//			popupKind = POPUP_COUNTRY;
//			showDialog_Country();
//		} else if(OnDataSyncCompleteListener.RESULT_GOTO_TERM == resultCode){
////			Intent intent = new Intent(this, TermsActivity.class);
////			startActivityForResult(intent, 3000);
//			Util.startActivity(this, TermsActivity.class, 3000);
//		} else {
//			RWDialog.showAlert(this,getString(R.string.app_name), getString(R.string.sp_service_unavailable_NORMAL));
//		} 
//
//	}

//	public void getLoginInfo(final HashMap<String, String> idMap) {
////		RWDialog.showProgress(this);
//
//		new AsyncTask<String, Void, LoginInfo>() {
//			private String strResult = "";
//			private InputStream Resp;
//
//			protected LoginInfo doInBackground(String... x) {
//
//				try {
//					Resp = HttpManager.getLGWorldExcute(TypingBattleLoginActivity.this, Define.SERVER_URL_LG_LOGIN, idMap);
//
//					BufferedReader reader = new BufferedReader(new InputStreamReader(Resp, "utf-8"), 8);
//					StringBuilder sb = new StringBuilder();
//					String line = null;
//					while ((line = reader.readLine()) != null) {
//						sb.append(line).append("\n");
//					}
//					strResult = sb.toString();
//					Util.log("login Result = " + strResult);
//					if (HttpManager.parser("result", strResult) == null || HttpManager.parser("result", strResult).equals("900")) {
//						Element e = HttpManager.getParser(strResult);
//						LoginInfo returnValue = new LoginInfo();
//						returnValue = new LoginInfo(e, 0);
//						return returnValue;
//					}
//
//				} catch (Exception e) {
//					Util.logError(e);
//				}
//				return null;
//			}
//			protected void onPreExecute() {
//				RWDialog.showProgress(TypingBattleLoginActivity.this);
//				
//			};
//			protected void onPostExecute(LoginInfo result) {
//				RWDialog.closeProgress(TypingBattleLoginActivity.this);
//				if(result == null){
//					Define.LGWC_COOKIE = "";
////					RWDialog.closeProgress(LoginActivity.this);
//					RWPreference.getInstance(TypingBattleLoginActivity.this).removeData(Define.COOKIE);
//					RWDialog.showAlert(TypingBattleLoginActivity.this,getString(R.string.app_name), getString(R.string.sp_service_unavailable_NORMAL));
//					return;
//				}
//				
//				
//				LoginInfo.setLoginInfo(result);
//				Util.log("result =" + result.getMsg());
//				Util.log("End login");
//				// onSyncComplete(OnDataSyncCompleteListener.RESULT_SYNC);
//
//				try {
//					
//					if (result.getCode() == null) {
//						Define.LGWC_COOKIE = "";
//						RWPreference.getInstance(TypingBattleLoginActivity.this).removeData(Define.COOKIE);
//						RWDialog.showAlert(TypingBattleLoginActivity.this, R.string.sp_service_unavailable_NORMAL);
//						return;
//					} else if(!result.getCode().equals("900")) {
//						Define.LGWC_COOKIE = "";
//						RWPreference.getInstance(TypingBattleLoginActivity.this).removeData(Define.COOKIE);
//						String msg = result.getMsg();
//						if ((msg.toLowerCase().indexOf("fail")>-1)|| (msg.toLowerCase().indexOf("invalid")>-1)) {
//							msg = getString(R.string.sp_Signin_ID_error_3_Mod_NORMAL);
//						}
//						
//						RWDialog.showAlert(TypingBattleLoginActivity.this, msg);
//						return;
//					}
//
//					prefer.setData(Define.SHARED_LOGIN_ID, et_id.getText().toString().trim());
//					prefer.setData(Define.SHARED_LOGIN_PWD, et_pwd.getText().toString().trim());
//					// RWPreference.getInstance(LoginActivity.this).setData(Define.SHARED_LOGIN_STATUS,
//					// true);
//
//					prefer.setData(Define.SHARED_LOGIN_EMAIL, result.getEmail());
//					prefer.setData(Define.SHARED_LOGIN_GENDER, result.getGender());
//					prefer.setData(Define.SHARED_LOGIN_BDATE, result.getBdate());
//					prefer.setData(Define.SHARED_LOGIN_COUNTRYCODE, result.getCountryCode());
//					prefer.setData(Define.SHARED_LOGIN_LANGUAGECODE, result.getLanguageCode());
//					prefer.setData(Define.SHARED_LOGIN_NETWORKCODE, result.getNewtwork());
//
//					Define.LoginID = prefer.getData(Define.SHARED_LOGIN_ID, "");
//
//					Util.log("email = " + result.getEmail());
//					Util.log("gender = " + result.getGender());
//					Util.log("bdate = " + result.getBdate());
//					Util.log("countrycode = " + result.getCountryCode());
//					Util.log("languagecode = " + result.getLanguageCode());
//					Util.log("network = " + result.getNewtwork());
//
//					HashMap<String, String> map = new HashMap<String, String>();
//					map.put("userid", et_id.getText().toString().trim());
//					map.put("password", et_pwd.getText().toString().trim());
//					map.put("passwordex", Util.makeSHA512(et_id.getText() .toString().trim(), et_pwd.getText().toString().trim()));
//
//					getLGRWTerms(map);
//
//					// setResult(RESULT_OK);
//					// finish();
//				} catch (Exception e) {
//					Define.LGWC_COOKIE = "";
////					RWDialog.closeProgress(LoginActivity.this);
//					Util.logError(e);
//					return;
//				}
//
//			}
//		}.execute();
//	}
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	{     
		super.onActivityResult(requestCode, resultCode, data);     
		if(resultCode == LOGIN_RESULT_REGISTER) {
			autoLogin();
		}
//		if(resultCode == LOGIN_RESULT_OK) {
//			setResult(LOGIN_RESULT_OK);
//			Log.d("","Login onActivityResult Result ok.");
//			finish();
//		}else if(resultCode == LOGIN_RESULT_FAILED) {
//			Toast.makeText(this, "login failed", Toast.LENGTH_LONG).show();
//		}
		
	}
	public void autoLogin(){
		ServerComunicationDTO dto = new ServerComunicationDTO();
		dto.setUserEmail(mgr.getData(PreferenceMgr.USER_EMAIL_KEY,""));
		dto.setUserPassword(mgr.getData(PreferenceMgr.USER_PASSWORD_KEY,""));
		//dto.setUserPassword("asdf1234");
		dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_STRING);
		try{
			Log.d("로그인시작","시작");
			ServerComunicationUtil.SESSION_KEY = (String)ServerComunicationUtil.login(dto,this);
			Log.d("", "SESSION_KEY===>>"+ServerComunicationUtil.SESSION_KEY);
			if("FAIL".equals(ServerComunicationUtil.SESSION_KEY)){
				//실패닷.
				loginFailed();
			}else{
				loginSuccess(dto);
			}
		}catch(Exception e){
			e.printStackTrace();
			loginFailed();
			//Log.d("에러에러",e);
		}
	}
	
	public void reqLogin(){
		ServerComunicationDTO dto = new ServerComunicationDTO();
		dto.setUserEmail(et_id.getText().toString().trim());
		dto.setUserPassword(et_pwd.getText().toString().trim());
		//dto.setUserPassword("asdf1234");
		dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_STRING);
		try{
			Log.d("로그인시작","시작");
			ServerComunicationUtil.SESSION_KEY = (String)ServerComunicationUtil.login(dto,this);
			if("FAIL".equals(ServerComunicationUtil.SESSION_KEY)){
				//실패닷.
				loginFailed();
			}else{
				loginSuccess(dto);
			}
		}catch(Exception e){
			e.printStackTrace();
			loginFailed();
			//Log.d("에러에러",e);
		}
	}

	private void loginSuccess(ServerComunicationDTO dto){
		mgr.setData(PreferenceMgr.USER_EMAIL_KEY,dto.getUserEmail());
		mgr.setData(PreferenceMgr.USER_PASSWORD_KEY,dto.getUserPassword());
    	Toast toast = Toast.makeText(this, getString(R.string.toast_login_success),
				Toast.LENGTH_SHORT);
		toast.show();
		Intent intent = new Intent(this,TypingBattleMainActivity.class);
		startActivity(intent);
		finish();
	}
	private void loginFailed(){
		mgr.setData(PreferenceMgr.USER_EMAIL_KEY,"");
		mgr.setData(PreferenceMgr.USER_PASSWORD_KEY,"");
    	Toast toast = Toast.makeText(this, getString(R.string.toast_login_failed),
				Toast.LENGTH_LONG);
		toast.show();
		
	}
	
	public void checkInput(){
		
		String str = "^([\\w-]+(?:\\.[\\w-]+)*)@((?:[\\w-]+\\.)*\\w[\\w-]{0,66})\\.([a-z]{2,6}(?:\\.[a-z]{2})?)$";
		Pattern p = Pattern.compile(str);
		
		Matcher m = p.matcher(et_id.getText().toString()); 

//        System.out.println("source:"+et_id.getText().toString()); 
        
		
        String msg = null;
        if(!m.find()){
        	msg = "이메일형식이 맞지 않습니다.";
        	Log.d("email TEST", "not match");
        }else if("".equals(et_pwd.getText().toString().trim())){
        	msg = "패스워드를 입력해주세요.";
        	Log.d("password TEST", "not match");
        }
        
        if(msg != null){
        	Toast toast = Toast.makeText(this, msg,
    				Toast.LENGTH_SHORT);
//    		toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 150);
    		toast.show();
    		return;
        }else{
        	reqLogin();
        }
	}
}
